/*
 * The Clear BSD License
 * Copyright (c) 2016, Freescale Semiconductor, Inc.
 * Copyright 2016-2017 NXP
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted (subject to the limitations in the disclaimer below) provided
 *  that the following conditions are met:
 *
 * o Redistributions of source code must retain the above copyright notice, this list
 *   of conditions and the following disclaimer.
 *
 * o Redistributions in binary form must reproduce the above copyright notice, this
 *   list of conditions and the following disclaimer in the documentation and/or
 *   other materials provided with the distribution.
 *
 * o Neither the name of the copyright holder nor the names of its
 *   contributors may be used to endorse or promote products derived from this
 *   software without specific prior written permission.
 *
 * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

//#include "fsl_common.h"
#include "fsl_debug_console.h"
#include "fsl_lpi2c.h"
#include "fsl_gpio.h"
#include "i2c_TSC2007.h"
#include "board.h"

#define MAX_POINT_NUM     13  //�������ʱ�򣬽��ܵ������������ֵ��һ�δ���������������ֵ
#define MIN_POINT_NUM     4   //���������ʱ�򣬽��ܵ�����������Сֵ��С�����ֵ��Ϊ��û�д���

POINT Point_Array[MAX_POINT_NUM];
POINT Pre_Touch_Point;
int K_X;
int K_Y;
bool XY_Change_Flag;   //�Ƿ����X Y ת��
POINT Ref_Point_Logic;//��������ת��(�߼�����ת��Ϊ��������)�Ĳο�������(�߼�����)��ѡ���һ��У׼����Ϊ�ο���
uint8_t I2C_EEPROM_dataBuff[8];
#define I2C_EEPROM_Addr    0x50
POINT Ref_Point_Logic;
volatile bool g_InputSignal = false;


void delay(uint32_t  Count)
{
    volatile uint32_t i = 0;
    for (i = 0; i < Count; ++i)
    {
        __asm("NOP"); /* delay */
    }
}
bool CheckSum(uint8_t *dataBuff,uint8_t  dataLen)
{
	 int i,sum=0;
   for (i=0;i<dataLen-1;i++)
	 {
     sum+=dataBuff[i];
	 }
   if(sum>0xff)
   {
       sum=~sum;
       sum+=1;
   }
   sum=sum&0xff;
	 if((sum == dataBuff[dataLen-1])&&(sum!=0))
	 {
			 return 1;
	 }
	return 0;
}

void TSC2007_PEN_IRQHandler(void)
{
    /* clear the interrupt status */
    GPIO_PortClearInterruptFlags(TSC2007_PEN_IRQ_GPIO, 1U << TSC2007_PEN_IRQ_GPIO_PIN);
    /* Change state of switch. */
    g_InputSignal = true;
    /* Add for ARM errata 838869, affects Cortex-M4, Cortex-M4F Store immediate overlapping
      exception return operation might vector to incorrect interrupt */
#if defined __CORTEX_M && (__CORTEX_M == 4U)
    __DSB();
#endif
}



///////////////��ʼ���ж�pin/////////////////////////
void TSC2007_InitIRQPins()
{
    IOMUXC_SetPinMux(
        IOMUXC_GPIO_AD_B0_11_GPIO1_IO11,          /* WAKEUP is configured as GPIO5_IO00 */
        0U);                                    /* Software Input On Field: Input Path is determined by functionality */

//		 IOMUXC_SetPinMux(
//      IOMUXC_GPIO_AD_B0_00_GPIO1_IO00,          /* WAKEUP is configured as GPIO5_IO00 */
//      0U);

}


/////////////////////TSC2007��ʼ��///////////////////////////
void I2C_TSC2007_Init()
{
    Pre_Touch_Point.X = -1;
    Pre_Touch_Point.Y = -1;

    Ref_Point_Logic.X = 0;
    Ref_Point_Logic.Y = 0;
    XY_Change_Flag = 0;
    gpio_pin_config_t sw_config =
    {
        kGPIO_DigitalInput, 1,
        kGPIO_IntFallingEdge,
    };


    TSC2007_InitIRQPins();
    /* Init input  GPIO. */
    EnableIRQ(TSC2007_PEN_IRQ);
    GPIO_PinInit(TSC2007_PEN_IRQ_GPIO, TSC2007_PEN_IRQ_GPIO_PIN, &sw_config);

    /* Enable GPIO pin interrupt */
    GPIO_PortEnableInterrupts(TSC2007_PEN_IRQ_GPIO, 1U << TSC2007_PEN_IRQ_GPIO_PIN);


    delay(80000);


    memset(I2C_EEPROM_dataBuff,0,8);
    BOARD_Touch_I2C_Receive(I2C_EEPROM_Addr,0x00,0x01,I2C_EEPROM_dataBuff,8);
	K_X = I2C_EEPROM_dataBuff[0];
	K_Y = I2C_EEPROM_dataBuff[1];
	Ref_Point_Logic.X |= I2C_EEPROM_dataBuff[2];
	Ref_Point_Logic.X = (Ref_Point_Logic.X<<8)|I2C_EEPROM_dataBuff[3];

	Ref_Point_Logic.Y |= I2C_EEPROM_dataBuff[4];
	Ref_Point_Logic.Y = (Ref_Point_Logic.Y<<8)|I2C_EEPROM_dataBuff[5];

	XY_Change_Flag = I2C_EEPROM_dataBuff[6];
}


/////////////////////�����õ�����ֵ/////////////////////////////
status_t  Get_TSC2007_MeasureResult(TSC2007_CMD_12BIT_t   cmd, uint8_t *dataBuff)
{
    status_t   ret_sta;

    if(!(ret_sta = BOARD_Touch_I2C_Send(TSC2007Add,0,0,&cmd,1)))//д����
    {
        //	  PRINTF("Write to EEPROM Sucess!!! dataBuff = %x\r\n",cmd);
    }
    else
    {
        PRINTF("Write to tsc2007 FAILD!!!!!!!!!!!!!!!!!!!!!!!!!!! dataBuff = %X   error = %d    &&&&&&&&&\r\n",cmd,ret_sta);
        return ret_sta;
    }

    delay(80000);

    memset(dataBuff,0,2);

    if(!(ret_sta = BOARD_Touch_I2C_Receive(TSC2007Add,0,0,dataBuff,2)))//������
    {
        //	  PRINTF("Read from TSC2007  X_COOR Sucess!!! dataBuff[0] = %x  dataBuff[1] = %x \r\n",dataBuff[0],dataBuff[1]);
    }
    else
    {
        PRINTF("Read from TSC2007  X_COOR   Faild!!! dataBuff[0] = %x  dataBuff[1] = %x \r\n",dataBuff[0],dataBuff[1]);
    }
    return ret_sta;

}



void Return_to_PWRDOWN()
{
    uint8_t dataBuff = 0x00;
    status_t   ret_sta;
    delay(80000);

    if(!(ret_sta = BOARD_Touch_I2C_Send(TSC2007Add,0,0,&dataBuff,1)))//д����
    {
//        PRINTF("Write to EEPROM Sucess!!! dataBuff = %x\r\n",dataBuff);
    }
    else
    {
        PRINTF("Write to tsc2007 FAILD!!!!!!!!!!!!!!!!!!!!!!!!!!! dataBuff = %X   error = %d    &&&&&&&&&\r\n",dataBuff,ret_sta);
    }
    delay(80000);

    g_InputSignal = false;
}





/*
//�������PPoint_Data_Filter ���������˲�
//������ point_array �������ݶ��л���
//������ len         �������ݶ��г��ȡ�
//������ touch_point �˲�֮�������
//������ touch_coor_type �������ͣ��߼�����OR�������꣩
//����ֵ��1���˲��ɹ� �õ����ꣻ0��ʧ�ܣ�δ�õ�����
*/
bool  Point_Data_Filter(POINT* point_array,int len,POINT *touch_point,touch_coor_type_t touch_coor_type)
{
    int temp_Avg_X = 0,temp_Avg_Y = 0;
    int Sum_X= 0,Sum_Y = 0;
    int i=0;
    bool  Ret = 0;

    for( i=1; i<(len-2); i++) //������һ���������������
    {
        Sum_X+=point_array[i].X;
        Sum_Y+=point_array[i].Y;
    }
    //averageƽ��ֵ

    temp_Avg_X = Sum_X/(len-3);
    temp_Avg_Y = Sum_Y/(len-3);

    if(touch_coor_type == Logic_Coor)
    {
        touch_point->X = temp_Avg_X;
        touch_point->Y = temp_Avg_Y;
        Ret = 1;
    }
    else if(touch_coor_type == Phy_Coor)
    {
        //ͨ�����㹫ʽ����
        if(XY_Change_Flag)
        {
            touch_point->X = abs(temp_Avg_Y-Ref_Point_Logic.X)*10/K_X + POINT0_PHY_X;
            touch_point->Y = abs(temp_Avg_X-Ref_Point_Logic.Y)*10/K_Y + POINT0_PHY_Y;
        }
        else
        {
            touch_point->X = abs(temp_Avg_X-Ref_Point_Logic.X)*10/K_X + POINT0_PHY_X;
            touch_point->Y = abs(temp_Avg_Y-Ref_Point_Logic.Y)*10/K_Y + POINT0_PHY_Y;
        }
        Ret = 1;
    }
    return Ret;

}




/*
//������Get_Touch_event �õ��������꣬�¼�
//������touch_point     ��������
//������touch_event     �¼�
//������touch_coor_type ������������ͣ��߼�����OR�������꣩
//����ֵ��1���д����¼���0���޴����¼�
*/

uint8_t Get_Touch_event(POINT *touch_point,touch_event_t *touch_event,touch_coor_type_t touch_coor_type)
{
    uint32_t counter = 0U;
    POINT Touch_Point;

    uint8_t dataBuff[2]= {0};
    uint32_t  X_VAL = 0;
    uint32_t  Y_VAL = 0;
    uint32_t  Z1_VAL = 0;
    uint32_t  Z2_VAL = 0;

    uint32_t  R_Touch;


    do
    {
        ////////////////////////////////////measure X///////////////////////////////

        Get_TSC2007_MeasureResult(Measure_X,dataBuff);
        X_VAL = ((uint16_t)(dataBuff[0])<<4)|(dataBuff[1]>>4);

//        PRINTF("Read TSC2007 X_VAL = %d \r\n",X_VAL);

        ////////////////////////////////////measure Y///////////////////////////////

        Get_TSC2007_MeasureResult(Measure_Y,dataBuff);

        Y_VAL = ((uint16_t)(dataBuff[0])<<4)|(dataBuff[1]>>4);

//        PRINTF("Read TSC2007 Y_VAL = %d \r\n",Y_VAL);

        ////////////////////////////////////measure Z1///////////////////////////////

        Get_TSC2007_MeasureResult(Measure_Z1,dataBuff);

        Z1_VAL = ((uint16_t)(dataBuff[0])<<4)|(dataBuff[1]>>4);

//			PRINTF("Read TSC2007 Z1_VAL = %d \r\n",Z1_VAL);

        ////////////////////////////////////measure Z2///////////////////////////////

        Get_TSC2007_MeasureResult(Measure_Z2,dataBuff);

        Z2_VAL = ((uint16_t)(dataBuff[0])<<4)|(dataBuff[1]>>4);

        //		PRINTF("Read TSC2007 Z2_VAL = %d \r\n",Z2_VAL);

        R_Touch = ((Z2_VAL-Z1_VAL)*X_VAL)/Z1_VAL;

        R_Touch*=PRESURE_PARAMETER;


//        PRINTF("Read TSC2007   R_Touch = %d  \r\n \r\n",R_Touch);

        delay(1600);
        Point_Array[counter].X = X_VAL;
        Point_Array[counter].Y = Y_VAL;
        counter++;
        //}while((R_Touch<8000)&&(R_Touch>1000)&&(counter<MAX_POINT_NUM));
    }
    while((R_Touch<80000)&&(R_Touch>100)&&(counter<MAX_POINT_NUM));


//			//////////////////�ɼ���MAX_POINT_NUM����������///////////////////////////////////////////
    if(counter==MAX_POINT_NUM)
    {
        ///////�����˲�,�õ�����������//////////////
        if(0 == Point_Data_Filter(Point_Array,counter,&Touch_Point,touch_coor_type))
        {
            counter = 0;
            return 0;
        }
        if((Pre_Touch_Point.X<0)&&(Pre_Touch_Point.Y<0))//˵����һ�����Ѿ��ͷ�
        {
            *touch_event = kTouch_Down;
            *touch_point = Touch_Point;
        }
        else//��һ��û���ͷ�
        {
            *touch_event = kTouch_Contact;
            *touch_point = Touch_Point;
        }
        Pre_Touch_Point = Touch_Point;
        counter = 0;
        return 1;
    }


    /////////////////////////////�ɼ����������ݸ�����IN_POINT_NUM��MAX_POINT_NUM֮��//////////////////////////////////////////////////////////////////////////
    if((counter<MAX_POINT_NUM)&&(counter>MIN_POINT_NUM))
    {

        ///////�����˲�,�õ�����������//////////////
        if(0 == Point_Data_Filter(Point_Array,counter,&Touch_Point,touch_coor_type))
        {
            counter = 0;
            return 0;
        }

        if((Pre_Touch_Point.X<0)&&(Pre_Touch_Point.Y<0))//˵����һ�����Ѿ��ͷ�
        {
            *touch_event = kTouch_Down;
            *touch_point = Touch_Point;

        }
        else//��һ��û���ͷ�
        {
            *touch_event = kTouch_Contact;
            *touch_point = Touch_Point;
        }
        Pre_Touch_Point = Touch_Point;
    }
    /////////////�ɼ��������ݵ���С����Сֵ����Ϊ������������޲�����counter = 0�������ǰ��point�Ǹ�ֵ�����ʾ��һ�����Ѿ��ͷţ����Ϊ��ֵ����δ�ͷţ����¼�ΪKeyUP////////
    else
    {
        if((Pre_Touch_Point.X<0)&&(Pre_Touch_Point.Y<0))//˵����һ�����Ѿ��ͷ�
        {
            counter = 0;
            Return_to_PWRDOWN();//////////////////////////////////
            return 0;
        }
        else//��һ��û���ͷ�
        {
            *touch_event = kTouch_Up;
            *touch_point = Pre_Touch_Point;//�ͷ���һ����
            Pre_Touch_Point.X = -1;
            Pre_Touch_Point.Y = -1;
            Return_to_PWRDOWN();
        }
    }
    counter = 0;
    return 1;
}







